import 'dart:math';

import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

final class ImagePageCubit extends Bloc<ImagePageEvent, ImagePageState> {

  ImagePageCubit() : super(ImagePageState.loading()) {
    on<ImagePageMoveEvent>((event, emit) {
      _move(state, event.x, event.y);
    });
    on<ImagePageScaleStartEvent>((event, emit) {
      _scaleStart(state);
    });
    on<ImagePageScaleEvent>((event, emit) {
      _scale(state, event.scale);
    });
  }

  _move(ImagePageState oldState, double x, double y) {
    emit(oldState.copy(x:x, y: y));
  }

  _scaleStart(ImagePageState oldState) {
    emit(oldState.copy(previousScale: oldState.scale));
  }

  _scale(ImagePageState oldState, double scale) {
    emit(oldState.copy(scale: oldState.previousScale * scale));
  }
}

final class ImagePageState extends Equatable {

  double x;
  double y;
  double scale;
  double previousScale;

  ImagePageState._({
    this.x = 0,
    this.y = 0,
    this.scale = 1.0,
    this.previousScale = 1.0
  });

  ImagePageState copy({ double? x, double? y, double? scale, double? previousScale}) {
    return ImagePageState._(
      x: x ?? this.x,
      y: y ?? this.y,
      scale: scale ?? this.scale,
      previousScale: previousScale ?? this.previousScale
    );
  }

  ImagePageState.loading() : this._();

  @override
  List<Object?> get props => [x, y, scale, previousScale];

}

abstract class ImagePageEvent {}
final class ImagePageMoveEvent extends ImagePageEvent {
  final double x;
  final double y;

  ImagePageMoveEvent(this.x, this.y);
}

final class ImagePageScaleStartEvent extends ImagePageEvent {
}

final class ImagePageScaleEvent extends ImagePageEvent {
  final double scale;

  ImagePageScaleEvent(this.scale);
}